'''struct 解决粘包现象'''
'''TCP 协议实现：客户端发送命令’并接收服务端发送过来的消息'''
from socket import *
import struct,json
ip_port=('localhost',51590)
buffer_size=1024
tcp_clent = socket(AF_INET,SOCK_STREAM)
tcp_clent.connect_ex(ip_port)
while True:
    msg = input("请输入字符串：>>>").strip()
    if not msg:continue
    if msg=="quit":break
    tcp_clent.send(msg.encode("utf-8"))
    try:
        heard = tcp_clent.recv(4)
        heard_json_len=struct.unpack("i",heard)[0]
        heard_json=json.loads(tcp_clent.recv(heard_json_len).decode("utf-8"))
        data_len=heard_json['data_size']
        recv_size=0
        recv_data=b''

        while recv_size<data_len:
            recv_data+=tcp_clent.recv(buffer_size)
            recv_size+=len(recv_data)
            print("命令执行的结果是:",recv_data.decode("gbk")) # 默认打开文件的编码为unicode默认编码是“gbk”
    except Exception:
        print(Exception)
tcp_clent.close()
